package com.cn.app;

import javax.servlet.ServletContext;

import org.springframework.context.ApplicationContext;

/**
 * FUN: 
 *
 * @author sushy
 * @date 2016-3-23 
 */
public class AppContext {


	/**
	 * Spring ApplicationContext
	 */
	private static ApplicationContext applicationContext;

	private static ServletContext servletContext;

	static void setApplicationContext(ApplicationContext applicationContext) {
		AppContext.applicationContext = applicationContext;
	}

	public static ApplicationContext getApplicationContext() {
		return AppContext.applicationContext;
	}

	public static ServletContext getServletContext() {
		return servletContext;
	}

	static void setServletContext(ServletContext servletContext) {
		AppContext.servletContext = servletContext;
	}

	public static Object getBean(String beanName) {
		if (applicationContext == null) {
			return null;
		}

		try {
			Object obj = applicationContext.getBean(beanName);
			if (obj != null) {
				return obj;
			}
		} catch (Throwable ignore) {
		}

		try {
			ClassLoader clsLoader = applicationContext.getClassLoader();
			Class<?> cls = clsLoader.loadClass(beanName);
			Object obj = applicationContext.getBean(cls);
			if (obj != null) {
				return obj;
			}
		} catch (Throwable ignore) {
		}

		return null;
	}


}
